package com.sa.token.config;

import cn.dev33.satoken.interceptor.SaRouteInterceptor;
import cn.dev33.satoken.router.SaRouter;
import cn.dev33.satoken.stp.StpUtil;
import com.sa.token.dto.response.menu.PermsResponse;
import com.sa.token.mapper.SysMenuMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.servlet.config.annotation.InterceptorRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import javax.annotation.Resource;
import java.util.List;

/**
 * @desc:
 * @author: xhs
 * @date: 2021/8/19 13:26
 * @version: JDK 1.8
 */
@Configuration
public class SaTokenConfigure implements WebMvcConfigurer {

    @Resource
    private SysMenuMapper menuMapper;

    /**
     * 注册拦截器
     *
     * @param registry
     */
    @Override
    public void addInterceptors(InterceptorRegistry registry) {

        // 注册Sa-Token的路由拦截器，并排除登录接口或其他可匿名访问的接口地址 (与注解拦截器无关)
        registry.addInterceptor(new SaRouteInterceptor())
                .addPathPatterns("/**")
                // 排除注册登录接口不需要鉴权
                .excludePathPatterns("/register")
                .excludePathPatterns("/login");

        // 注册Sa-Token的路由拦截器，拦截是否有权限访问接口
        registry.addInterceptor(new SaRouteInterceptor((req, res, handler) -> {
            // 查询所有的接口地址及接口权限标识
            List<PermsResponse> permsList = menuMapper.getInterfaceInfo();
            for (PermsResponse per : permsList) {
                SaRouter.match(per.getPath(), r -> StpUtil.checkPermission(per.getPerms()));
            }
        }));
    }
}
